package com.ychs.dpmms.service;

import com.ychs.dpmms.dao.*;
import com.ychs.dpmms.entity.*;
import com.ychs.dpmms.util.Constants;
import com.ychs.dpmms.util.DateUtil;
import org.apache.ibatis.annotations.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * copyright(c)2021 YYB.ALL rights Reserved
 * <p>
 * 描述:
 *
 * @author 原玉波
 * @version 1.0
 * @date 2021/9/16
 */
@Component
public class AutoService {
    //slf4j日志对象
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    //引入mapper
    @Resource
    private BranchMapper branchMapper;
    @Resource
    private SecondOrganizationMapper secondOrganizationMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private DeveloperMapper developerMapper;
    @Resource
    private ReportMapper reportMapper;
    @Resource
    private NoticeMapper noticeMapper;
    //@Scheduled(fixedDelay = )每个任务结束，等待指定时间再次执行



    @Scheduled(cron="0 0 0 1 1 *") // 每年执行一次此方法
    //清理无效账户
    public void clearUselessUser(){
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("state", 0);
        List<User> userList = userMapper.select(conditions);
        for (int k = 0; k < userList.size(); k++) {
            conditions = new HashMap<>();
            conditions.put("user", userList.get(k).getId());
            List<Developer> developerList = developerMapper.select(conditions);
            if (developerList.size() > 0) {
                for (int i = 0; i < developerList.size(); i++) {
                    conditions = new HashMap<>();
                    conditions.put("developer", developerList.get(i).getId());
                    List<Report> reportList = reportMapper.select(conditions);
                    if (reportList.size() > 0) {
                        for (int j = 0; j < reportList.size(); j++) {
                            reportMapper.delete(reportList.get(j).getId());
                        }
                    }
                    developerMapper.delete(developerList.get(i).getId());
                }
            }
            boolean result = userMapper.delete(userList.get(k).getId()) == Constants.UPDATE_SUCCESS;
            if(!result){
                break;
            }
        }
        logger.debug("执行清楚无效账号完毕");
    }

    @Scheduled(cron="0 59 23 * * ?")//每天的23分59秒执行
    public void setDeveloperPushPositiveStatus() {
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("capacity", 1);//身份入党申请人
        conditions.put("pushPositiveStatus", 1);//通过积极分子推选
        List<Developer> developerList = developerMapper.select(conditions);
        for (int i = 0; i < developerList.size(); i++) {
            Date pushPositiveDate = developerList.get(i).getPushPositiveDate();
            SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
            Date after720 = new Date(pushPositiveDate.getTime() + 720 * 24 * 60 * 60 * 1000);
            Date now = new Date();
            if (after720.before(now)) {
                Developer developer = developerList.get(i);
                developer.setPushDevelopStatus(0);
                boolean result = developerMapper.update(developer)== Constants.UPDATE_SUCCESS;
            }
        }
        logger.debug("执行积极分子重新推优完毕");
    }

    @Scheduled(cron="0 59 23 * * ?")//每天的23分59秒执行
    public void setDeveloperPushDevelopStatus() {
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("capacity", 2);//身份积极分子
        conditions.put("pushDevelopStatus", 1);//通过发展对象推选
        List<Developer> developerList = developerMapper.select(conditions);
        for (int i = 0; i < developerList.size(); i++) {
            Date pushDevelopDate = developerList.get(i).getPushDevelopDate();
            SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
            Date after720 = new Date(pushDevelopDate.getTime() + 720 * 24 * 60 * 60 * 1000);
            Date now = new Date();
            if (after720.before(now)) {
                Developer developer = developerList.get(i);
                developer.setPushDevelopStatus(0);
                boolean result = developerMapper.update(developer)== Constants.UPDATE_SUCCESS;
            }
        }
        logger.debug("执行发展对象重新推优完毕");
    }

    @Scheduled(cron="0 59 23 * * ?")//每天的23分59秒执行
    public void setCollegeClassStatus() {
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("capacity", 2);//身份发展对象
        conditions.put("collegeClassStatus", 1);
        List<Developer> developerList = developerMapper.select(conditions);
        for (int i = 0; i < developerList.size(); i++) {
            Date collegeClassDate = developerList.get(i).getCollegeClassDate();
            Date after730 = new Date(collegeClassDate.getTime() + 730 * 24 * 60 * 60 * 1000);
            Date now = new Date();
            if (after730.before(now)) {
                Developer developer = developerList.get(i);
                developer.setCollegeClassStatus(0);
                boolean result = developerMapper.update(developer)== Constants.UPDATE_SUCCESS;
            }
        }
        logger.debug("执行校党课重新培训完毕");
    }

    @Scheduled(cron="0 59 23 * * ?")//每天的23分59秒执行
    public void setSchoolClassStatus() {
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("capacity", 3);//身份发展对象
        conditions.put("schoolClassStatus", 1);
        List<Developer> developerList = developerMapper.select(conditions);
        for (int i = 0; i < developerList.size(); i++) {
            Date schoolClassDate = developerList.get(i).getSchoolClassDate();
            Date after365 = new Date(schoolClassDate.getTime() + 365 * 24 * 60 * 60 * 1000);
            Date now = new Date();
            if (after365.before(now)) {
                Developer developer = developerList.get(i);
                developer.setSchoolClassStatus(0);
                boolean result = developerMapper.update(developer)== Constants.UPDATE_SUCCESS;
            }
        }
        logger.debug("执行校党课重新培训完毕");
    }

    @Scheduled(cron="0 59 23 * * ?")//每天的23分59秒执行,发送信息给三级管理员
    public void setNoticeToThird() {
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("capacity", 1);
        conditions.put("talkPassStatus", 0);
        List<Developer> developerList = developerMapper.select(conditions);
        if (developerList != null) {
            for (int i = 0; i < developerList.size(); i++) {
                Date submitEnterApplicationDate = developerList.get(i).getSubmitEnterApplicationDate();
                Date after20 = new Date(submitEnterApplicationDate.getTime() + 20 * 24 * 60 * 60 * 1000);
                Date now = new Date();
                if (after20.before(now)) {
                    Developer developer = developerList.get(i);
                    User user = developer.getUser();
                    Branch branch = user.getBranch();
                    SecondOrganization secondOrganization = user.getSecondOrganization();

                    conditions = new HashMap<>();
                    conditions.put("branch", branch.getId());
                    conditions.put("secondOrganization", secondOrganization.getId());
                    conditions.put("role", 2);//三级管理员
                    List<User> userList = userMapper.select(conditions);
                    if (userList != null) {
                        for (int j=0; j < userList.size(); j++) {
                            Notice notice = new Notice();
                            notice.setContent("您还有尚未进行谈话的人员:  "+developer.getName());
                            notice.setToUser(userList.get(j));
                            notice.setState(0);
                            notice.setSendDate(new Date());
                            boolean result = noticeMapper.insert(notice) == Constants.UPDATE_SUCCESS;
                        }
                    }
                }
            }
        }
        logger.debug("执行通知二级管理员完毕");
    }



    @Scheduled(cron="0 59 23 * * ?")//每天的23分59秒执行,发送信息给二级管理员
    public void setNoticeToSecond() {
        List<Integer> branchIds = new ArrayList<>();
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("capacity", 1);
        conditions.put("talkPassStatus", 0);
        List<Developer> developerList = developerMapper.select(conditions);
        if (developerList != null) {
            //首先找出规定时间30天都没完成谈话的人员，并拿到他们的党支部id
            for (int i = 0; i < developerList.size(); i++) {
                Date submitEnterApplicationDate = developerList.get(i).getSubmitEnterApplicationDate();
                Date after30 = new Date(submitEnterApplicationDate.getTime() + 30 * 24 * 60 * 60 * 1000);
                Date now = new Date();
                if (after30.before(now)) {
                    Developer developer = developerList.get(i);
                    User user = developer.getUser();

                    branchIds.add(0,user.getBranch().getId());
                }
            }
            if (branchIds.size() > 0) {
                //去重
                branchIds = branchIds.stream().distinct().collect(Collectors.toList());
                List<Branch> branchList = new ArrayList<>();
                for (int i = 0; i < branchIds.size(); i++) {
                    branchList.add(0,branchMapper.selectById(branchIds.get(i)));
                }

                for (int i = 0; i < branchList.size(); i++) {
                    conditions = new HashMap<>();
                    conditions.put("secondOrganization", branchList.get(i).getSecondOrganization().getId());
                    conditions.put("role", 3);//二级管理员
                    List<User> userList = userMapper.select(conditions);
                    if (userList != null) {
                        for (int j=0; j < userList.size(); j++) {
                            Notice notice = new Notice();
                            notice.setContent(branchList.get(i).getName()+" 未完成党组织谈话");
                            notice.setToUser(userList.get(j));
                            notice.setState(0);
                            notice.setSendDate(new Date());
                            boolean result = noticeMapper.insert(notice) == Constants.UPDATE_SUCCESS;
                        }
                    }

                }
            }

        }
        logger.debug("执行通知三级管理员完毕");
    }

    //恢复登录状态，2分钟执行一次
    @Scheduled(fixedDelay=2*60*1000)
    public void resumeLogin() {
        List<String> loginState = new ArrayList<>();
        loginState.add("wait");
        loginState.add("loginFail1");
        loginState.add("loginFail2");
        loginState.add("loginFail3");
        for (int i = 0; i < loginState.size(); i++) {
            Map<String, Object> conditions = new HashMap<>();
            conditions.put("remark", loginState.get(i));
            List<User> userList = userMapper.select(conditions);
            for (int j = 0; j < userList.size(); j++) {
                User newUser = userList.get(j);
                newUser.setRemark("");
                boolean modifyResult = userMapper.update(newUser) == Constants.UPDATE_SUCCESS;
            }
        }
        logger.debug("执行恢复登录状态完毕");
    }
}
